package com.iter.devbox.httpclient;

import java.io.IOException;
import java.nio.CharBuffer;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.client.methods.AsyncCharConsumer;
import org.apache.http.nio.client.methods.HttpAsyncMethods;
import org.apache.http.nio.protocol.HttpAsyncRequestProducer;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

/**
 * 异步HttpClient工具
 * 
 * @author hnylj
 */
public class AsyncHttpClientUtils {
	
	public String doGetByBlockResult (String url) {
		CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
		try {
			// Start the client
		    httpclient.start();
		    // Execute request
		    HttpGet request = new HttpGet(url);
		    Future<HttpResponse> future = httpclient.execute(request, null);
		    // and wait until a response is received
		    HttpResponse response = future.get();
		    System.out.println(request.getRequestLine() + "->" + response.getStatusLine());
		    HttpEntity httpEntity = response.getEntity();
		    String result = EntityUtils.toString(httpEntity);
		    return result;
		} catch (ExecutionException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "";
	}

	public void doGetByFutureCallback (String url) {
		final CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
		// Start the client
	    httpclient.start();
	    // Execute request
	    final HttpGet request = new HttpGet(url);
	    httpclient.execute(request, new FutureCallback<HttpResponse>() {
            public void completed(final HttpResponse response) {
                System.out.println(request.getRequestLine() + "->" + response.getStatusLine());
                HttpEntity httpEntity = response.getEntity();
                try {
                	String result = EntityUtils.toString(httpEntity);
					System.out.println("Result: " + result);
				} catch (ParseException | IOException e) {
					e.printStackTrace();
				} finally {
		            try {
						httpclient.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
		        }
            }

            public void failed(final Exception ex) {
                System.out.println(request.getRequestLine() + "->" + ex);
                try {
					httpclient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
            }

            public void cancelled() {
                System.out.println(request.getRequestLine() + " cancelled");
                try {
					httpclient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
            }
        });
	}
	
	public void doGetByCharConsumer () {
        final CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
        httpclient.start();
        final HttpGet request3 = new HttpGet("http://www.apache.org/");
        HttpAsyncRequestProducer producer3 = HttpAsyncMethods.create(request3);
        AsyncCharConsumer<HttpResponse> consumer3 = new AsyncCharConsumer<HttpResponse>() {
            HttpResponse response;
            @Override
            protected void onResponseReceived(final HttpResponse response) {
                this.response = response;
            }

            @Override
            protected void onCharReceived(final CharBuffer buf, final IOControl ioctrl) throws IOException {
                // Do something useful
            	System.out.println(buf);
            }

            @Override
            protected void releaseResources() {
            	System.out.println("释放资源。。。。。。。。。。。。");
            	
            }

            @Override
            protected HttpResponse buildResult(final HttpContext context) {
            	System.out.println(response);
                return this.response;
            }

        };
        httpclient.execute(producer3, consumer3, new FutureCallback<HttpResponse>() {
            public void completed(final HttpResponse response3) {
            	System.out.println("完成。。。。。。。");
                System.out.println(request3.getRequestLine() + "->" + response3.getStatusLine());
                try {
					httpclient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
            }

            public void failed(final Exception ex) {
                System.out.println(request3.getRequestLine() + "->" + ex);
                try {
					httpclient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
            }

            public void cancelled() {
                System.out.println(request3.getRequestLine() + " cancelled");
                try {
					httpclient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
            }
        });
    }
}